import gradio as gr
import requests
import os
from dotenv import load_dotenv  # 需要安装python-dotenv

# 加载.env文件中的环境变量（可选）
load_dotenv()

# ================= 配置区 =================
API_BASE_URL = "https://api.deepseek.com/v1/chat/completions"  # DeepSeek API的URL
DEFAULT_MODEL = "deepseek-chat"  # 使用的模型名称


# =========================================

def get_api_key():
    """安全获取API密钥的优先级：环境变量 > 界面输入"""
    return os.getenv("DEEPSEEK_API_KEY")


def call_deepseek_api(prompt: str, api_key: str) -> str:
    """调用DeepSeek API"""
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }

    payload = {
        "model": DEFAULT_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 512
    }

    try:
        response = requests.post(
            API_BASE_URL,
            headers=headers,
            json=payload,
            timeout=30  # 设置超时防止长时间等待
        )
        response.raise_for_status()  # 自动触发HTTP错误异常

        result = response.json()
        return result['choices'][0]['message']['content']

    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            return "❌ 认证失败：请检查API密钥是否正确"
        return f"HTTP错误：{e.response.status_code} - {e.response.reason}"
    except requests.exceptions.Timeout:
        return "⏳ 请求超时，请稍后重试"
    except KeyError:
        return "🔍 响应解析错误，请检查API返回格式"
    except Exception as e:
        return f"⚠️ 未知错误：{str(e)}"


def generate_response(prompt: str, api_key: str):
    """带安全验证的处理函数"""
    if not api_key.strip():
        return "🔑 请先输入有效的API密钥"

    if not api_key.startswith("sk-"):
        return "⚠️ API密钥格式错误，应以'sk-'开头"

    return call_deepseek_api(prompt, api_key.strip())


# 创建界面
with gr.Blocks(title="DeepSeek智能助手", theme=gr.themes.Soft()) as app:
    gr.Markdown("# 🤖 DeepSeek智能问答系统")

    with gr.Tab("问答界面"):
        with gr.Row():
            api_key_input = gr.Textbox(
                label="API密钥",
                placeholder="在此输入您的DeepSeek API密钥...",
                type="password",
                info="推荐通过环境变量设置（安全）"
            )

        with gr.Row():
            input_prompt = gr.Textbox(
                label="输入问题",
                placeholder="请输入您的问题...",
                lines=3,
                max_lines=6
            )

        with gr.Row():
            submit_btn = gr.Button("提交问题", variant="primary")
            clear_btn = gr.Button("清空内容")

        with gr.Row():
            output_area = gr.Textbox(
                label="AI回复",
                interactive=False,
                lines=8,
                show_copy_button=True
            )

    # 交互逻辑
    submit_btn.click(
        fn=generate_response,
        inputs=[input_prompt, api_key_input],
        outputs=output_area
    )

    clear_btn.click(
        fn=lambda: ["", "", ""],
        inputs=[],
        outputs=[input_prompt, output_area, api_key_input]
    )

# 启动应用
if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0" if os.getenv("DOCKER_MODE") else None,
        server_port=int(os.getenv("PORT", 7860)),
        share=False,
        auth=(
            os.getenv("WEB_USERNAME"),
            os.getenv("WEB_PASSWORD")
        ) if os.getenv("WEB_AUTH") else None
    )